package com.lk.theurlpro.service.impl;

import com.lk.theurlpro.dao.AllUrlsMapper;
import com.lk.theurlpro.pojo.Allurls;
import com.lk.theurlpro.service.FileService;
import com.lk.theurlpro.util.DateUtil;
import com.lk.theurlpro.util.FileUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author lk
 * @date 2020/2/10 0010 11:24
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    AllUrlsMapper allUrlsMapper;

    @Override
    public String fileUpload(MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            ArrayList<Allurls> allurlsList = new ArrayList<>();
            // 读取文件内容
            Reader reader = null;
            reader = new InputStreamReader(file.getInputStream(), "utf-8");
            BufferedReader br = new BufferedReader(reader);
            String line;
            while ((line = br.readLine()) != null) {
                // 一次读入一行数据
                Allurls allurls = new Allurls();
                if (line != null && line != "") {
                    String[] content = line.split("，");
                    allurls.setU_title(content[0]);
                    allurls.setUrl(content[1]);
                    allurls.setType(content[2]);
                    allurls.setDate(DateUtil.getNowDate());
                }
                allurlsList.add(allurls);
            }
            reader.close();
            // 将文件内容写到数据库
            for (Allurls allurls : allurlsList) {
                allUrlsMapper.save(allurls);
            }

            return "成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "失败";
    }

    @Override
    public String htmlUpload(File file) {
        try {
            Document doc = Jsoup.parse(file, "UTF-8");
            Elements links = doc.select("dt > a[href]"); //link
            HashMap<String, String> map = new HashMap<>();
            for (Element link : links) {
                map.put(link.text(), link.attr("href"));
            }
            Allurls allurls = new Allurls();
            for (String s : map.keySet()) {
                allurls.setU_title(s);
                allurls.setUrl(map.get(s));
                allurls.setType(s);
                allurls.setDate(DateUtil.getNowDate());
                allUrlsMapper.save(allurls);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "失败";
        }finally {
            FileUtil.delteTempFile(file);
        }
        return "成功";
    }
}
